package com.example.baseweather.ui.view.TextView;


import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;


public class AnimatedTextView extends View {
    private Paint mPaint;
    private String mText = "这是一个测试的BitMap";
    private float[] mCharWidths;
    private float mProgress = 0f;
    private int mNormalColor = Color.BLACK;
    private int mHighlightColor = Color.RED;
    private float mNormalSize = 50f;
    private float mHighlightSize = 70f;

    public AnimatedTextView(Context context) {
        super(context);
        init();
    }

    public AnimatedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AnimatedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextSize(mNormalSize);
        setText(mText); // 初始化时设置文本
    }

    public void setText(String text) {
        mText = text;
        mCharWidths = new float[mText.length()];
        mPaint.getTextWidths(mText, mCharWidths);
        startAnimation();
    }

    public void setNormalColor(int color) {
        mNormalColor = color;
        invalidate();
    }

    public void setHighlightColor(int color) {
        mHighlightColor = color;
        invalidate();
    }

    public void setNormalSize(float size) {
        mNormalSize = size;
        invalidate();
    }

    public void setHighlightSize(float size) {
        mHighlightSize = size;
        invalidate();
    }

    private void startAnimation() {
        ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
        animator.setDuration(1000); // 动画持续时间
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mProgress = (float) animation.getAnimatedValue();
                invalidate(); // 触发重绘
            }
        });
        animator.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float x = 0;
        float y = getHeight() / 2;

        for (int i = 0; i < mText.length(); i++) {
            float progress = (float) i / mText.length();
            if (mProgress > progress) {
                // 高亮部分
                mPaint.setColor(mHighlightColor);
                mPaint.setTextSize(mHighlightSize);
            } else {
                // 普通部分
                mPaint.setColor(mNormalColor);
                mPaint.setTextSize(mNormalSize);
            }

            canvas.drawText(String.valueOf(mText.charAt(i)), x, 0+mPaint.getTextSize(), mPaint);
            x += mCharWidths[i];
        }
    }
}
